const db = require('../model')
const Order = db.order
const Account = db.accounts
const Op = db.Sequelize.Op
const formatTime = require('../utils/formatTime')

// 查询某用户的全部订单,根据 status 来查询
exports.findAll = async (req, res) => {
	const {
		ordName,
		page,
		pageSize,
		time = '0',
		ordSituation = '-1',
	} = req.query
	const where = {}
	const { userId } = req.session
	if (!userId) {
		return res.status(401).send({
			code: 0,
			message: '用户没有登录',
		})
	}
	where.userId = userId
	if (ordSituation !== '-1') {
		where.ordSituation = ordSituation
	}

	if (ordName) {
		const medName = {
			[Op.like]: `%${ordName}%`,
		}
		where.medName = medName
	}

	if (time !== '0') {
		const ordDate = {}
		switch (time) {
			case '1':
				ordDate[Op.gt] = new Date(new Date() - 90 * 24 * 60 * 60 * 1000)
				break
			case '2':
				ordDate[Op.between] = [
					'2021-01-01 00:00:00',
					'2021-12-31 24:00:00',
				]
				break
			case '3':
				ordDate[Op.between] = [
					'2020-01-01 00:00:00',
					'2020-12-31 24:00:00',
				]
				break
			case '4':
				ordDate[Op.lt] = '2020-01-01 00:00:00'
				break
		}
		where.ordDate = ordDate
	}

	const { rows, count } = await Order.findAndCountAll({
		where,
		order: [['ordDate', 'DESC']],
		limit: pageSize * 1,
		offset: pageSize * (page - 1) * 1,
		raw: true,
	})

	return res.status(200).send({
		code: 1,
		data: rows,
		count,
	})
}

// 新增订单操作
exports.createOne = async (req, res) => {
	const userId = req.session.userId
	const { userName } = await Account.findOne({
		attributes: ['userName'],
		where: { userId },
	})
	const params = req.body
	let { medPrice, ordCount } = params
	medPrice = medPrice * 1
	const ordTotalprice = medPrice * ordCount
	Object.assign(params, { userId, userName, ordTotalprice, medPrice })
	const orderData = Order.create(params)
	if (!orderData) {
		return res.status(500).send({
			code: -1,
			message: '服务端现在无法处理订单',
		})
	}

	return res.send({
		code: 1,
	})
}
//更新订单信息
exports.update = async (req, res) => {
	const params = req.body
	const updateList = []
	let i = 0
	params.forEach((item) => {
		const obj = {}
		obj.ordNo = item
		obj.ordSituation = 1
		updateList.push(obj)
	})

	await Order.bulkCreate(updateList, {
		updateOnDuplicate: ['ordSituation'],
	})

	return res.status(200).send({
		code: 1,
	})
}
//删除订单信息
exports.delete = async (req, res) => {
	const { ordNo } = req.body
	await Order.update(
		{
			ordSituation: 3,
		},
		{
			where: { ordNo },
		}
	)
	return res.status(200).send({
		code: 1,
	})
}
